"""
配置验证器
"""
import socket
from typing import Dict, List, Tuple, Any
from ..schemas.service_config import UnifiedConfig

class ConfigValidator:
    """配置验证器"""
    
    def __init__(self, config: UnifiedConfig):
        self.config = config
        self.errors: List[str] = []
        self.warnings: List[str] = []
    
    def validate(self) -> Tuple[bool, List[str], List[str]]:
        """执行完整验证"""
        self.errors.clear()
        self.warnings.clear()
        
        # 基础验证
        self._validate_ports()
        self._validate_database_connections()
        self._validate_external_dependencies()
        self._validate_security_config()
        
        return len(self.errors) == 0, self.errors.copy(), self.warnings.copy()
    
    def _validate_ports(self):
        """验证端口配置"""
        used_ports = set()
        
        for service_name, service in self.config.services.items():
            if not service.enabled:
                continue
                
            # 检查端口是否已被占用
            if service.port in used_ports:
                self.errors.append(f"端口冲突: {service.port} 被多个服务使用")
            else:
                used_ports.add(service.port)
            
            # 检查端口是否可用
            if self._is_port_in_use(service.host, service.port):
                self.warnings.append(f"端口 {service.port} 可能已被占用")
    
    def _validate_database_connections(self):
        """验证数据库连接"""
        for db_name, db_config in self.config.databases.items():
            # 这里可以添加实际的数据库连接测试
            if not db_config.host:
                self.errors.append(f"数据库 {db_name} 缺少主机配置")
            
            # 对于InfluxDB，检查bucket而不是database
            if db_config.type == "influxdb":
                if not getattr(db_config, 'bucket', None):
                    self.errors.append(f"InfluxDB {db_name} 缺少bucket配置")
                if not getattr(db_config, 'org', None):
                    self.errors.append(f"InfluxDB {db_name} 缺少org配置")
            else:
                # 对于其他数据库类型，检查database字段
                if not db_config.database:
                    self.errors.append(f"数据库 {db_name} 缺少数据库名配置")
    
    def _validate_external_dependencies(self):
        """验证外部依赖"""
        # Redis连接验证
        redis_config = self.config.cache.get('redis', {})
        if redis_config:
            redis_host = redis_config.get('host')
            redis_port = redis_config.get('port', 6379)
            
            if redis_host and self._is_port_in_use(redis_host, redis_port):
                self.warnings.append(f"Redis服务器 {redis_host}:{redis_port} 可能不可用")
    
    def _validate_security_config(self):
        """验证安全配置"""
        security = self.config.security
        
        # JWT密钥检查
        if security.jwt_secret_key == "your_secret_key_change_in_production":
            self.warnings.append("使用默认JWT密钥，生产环境请更换")
        
        if len(security.jwt_secret_key) < 32:
            self.warnings.append("JWT密钥长度过短，建议至少32字符")
    
    def _is_port_in_use(self, host: str, port: int) -> bool:
        """检查端口是否被占用"""
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.settimeout(1)
                result = s.connect_ex((host, port))
                return result == 0
        except:
            return False

def validate_config(config: UnifiedConfig) -> Dict[str, Any]:
    """验证配置并返回结果"""
    validator = ConfigValidator(config)
    is_valid, errors, warnings = validator.validate()
    
    return {
        "valid": is_valid,
        "errors": errors,
        "warnings": warnings,
        "summary": {
            "total_services": len(config.services),
            "enabled_services": len(config.get_enabled_services()),
            "total_databases": len(config.databases),
            "error_count": len(errors),
            "warning_count": len(warnings)
        }
    }
